package com.emeory.m3u8.core;

import com.emeory.m3u8.entry.VideoMeta;
import com.emeory.m3u8.exception.M3u8Exception;
import java.util.List;

public class M3u8VideoDownload {

  private String filePath;

  private VideoListFilter videoListFilter;
  private Downloader downloader;

  public M3u8VideoDownload(int threadCount) {
    downloader = new Downloader(threadCount);
  }

  private void checkField() {
    if (filePath == null) {
      throw new M3u8Exception("未正确设置存储路径");
    }
  }



  public void setVideoListFilter(VideoListFilter filter) {
    videoListFilter = filter;
  }

  public void setFilePath(String filePath) {
    this.filePath = filePath;
  }

  public void startDownload(String url, String fileName){
    checkField();
    UrlParseInit urlParseInit = new UrlParseInit(url, filePath, fileName);
    urlParseInit.initUrl();
    List<VideoMeta> videoMetaList = urlParseInit.getVideoList();
    if (videoListFilter == null){
      videoListFilter = new DefaultVideoFilter();
    }
    VideoMeta selectVideo;
    if (videoMetaList.size() > 1){
      selectVideo = videoListFilter.filter(videoMetaList);
    }else {
      selectVideo = videoMetaList.get(0);
    }
    startDownload(selectVideo);
  }

  public void startDownload(VideoMeta videoMeta){
    downloader.downloadVideo(videoMeta);
  }
}
